import type { User } from "~/stores/useAuthStore";

// 定义API响应类型
interface ApiResponse {
  newToken: any;
  message: string;
  errCode: number;
  success: boolean;
}
interface ApiGetChaptcha {
  captchaBase64: string;
  message: string;
  errCode: number;
  success: boolean;
}
export const useAuth = () => {
  const authStore = useAuthStore();

  // 登录
  const login = async (credentials: {
    username: string;
    password: string;
    code: string;
  }) => {
    try {
      const result = await $fetch<ApiResponse>("/newapi/auth/login", {
        method: "POST",
        body: credentials,
      }).catch((err) => {
        throw err;
      });
      if (result?.errCode === 0) {
        authStore.login(result);
        return {
          success: true,
          message: "登录成功",
        };
      }

      return {
        success: false,
        message: result.message,
      };
    } catch (error: any) {
      const errorMessage =
        error.data?.statusMessage || error.message || "登录失败";
      return {
        success: false,
        message: errorMessage,
      };
    }
  };

  // 注册
  const register = async (userData: {
    username: string;
    password: string;
    code: string;
  }) => {
    try {
      const result = await $fetch<ApiResponse>("/newapi/auth/register", {
        method: "POST",
        body: userData,
      });
      if (result?.errCode === 0) {
        return {
          success: true,
          message: "注册成功",
        };
      }
      return {
        success: false,
        message: result?.message || "注册失败",
      };
    } catch (error: any) {
      const errorMessage =
        error.data?.statusMessage || error.message || "注册失败";
      return {
        success: false,
        message: errorMessage,
      };
    }
  };

  // 登出
  const logout = () => {
    authStore.logout();
    console.log("已退出登录");
    navigateTo("/");
  };

  // 检查登录状态
  const checkAuth = () => {
    authStore.initAuth();
    return authStore.isLoggedIn;
  };
  // 获取验证码
  const getChaptcha = async () => {
    try {
      // 调用获取验证码图片接口
      const { errCode, message, captchaBase64, success } =
        await $fetch<ApiGetChaptcha>("/newapi/auth/getChaptcha", {
          method: "GET",
        });
      if (!success) {
        throw new Error(message || "获取验证码失败");
      }

      const responseData = {
        captchaBase64,
        message,
        errCode,
      };
      return responseData;
    } catch (err: any) {
      return {
        captchaBase64: "",
        message: err?.message || "验证码获取失败",
        errCode: 1,
      };
    }
  };
  return {
    login,
    register,
    logout,
    checkAuth,
    getChaptcha,
    isLoggedIn: computed(() => authStore.isLoggedIn),
    user: computed(() => authStore.user),
  };
};
